package com.tzq.bearstory;

import android.app.Activity;
import android.app.Notification;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import com.google.gson.Gson;
import com.tzq.bearstory.bean.MyPlayList;
import com.umeng.analytics.MobclickAgent;
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants;
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.album.BatchAlbumList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.appnotification.XmNotificationCreater;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.util.BaseUtil;
import com.ximalaya.ting.android.player.PlayCacheByLRU;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tzq.bearstory.MyPlayerReceiver.NOTIFICATION_ID;

public class MainActivity extends FlutterActivity {
    private static final String METHOD_CHANNEL = "dar.flutter.io/method_channel";
    private static final String EVENT_CHANNEL = "dar.flutter.io/event_channel";

    static String PLATFOEM_XMLY = "xmly";

    private FlutterEngine flutterEngine;

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        LogUtils.d("configureFlutterEngine--");
        this.flutterEngine = flutterEngine;
        addMethodChannel();
        addEventChannel();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarColor(this);

        XmNotificationCreater creater = XmNotificationCreater.getInstanse(this);
        Notification mNotification = creater.initNotification(this.getApplicationContext(), MainActivity.class);
        LogUtils.d("BaseUtil.isMainApp()--" + BaseUtil.isMainApp());
        XmPlayerManager.getInstance(getApplicationContext()).init(NOTIFICATION_ID, mNotification);
    }

    /**
     * 修改状态栏颜色，支持4.4以上版本
     *
     * @param activity
     */
    public static void setStatusBarColor(Activity activity) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        XmPlayerManager.getInstance(getApplicationContext()).init();
        PlayCacheByLRU.PLAY_CACHE_NUM = 10;//设置缓存数量
        XmPlayerManager.getInstance(getApplicationContext()).setBreakpointResume(false);//不记录播放记录，每次从头播放
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private int getBatteryLevel() {
        int batteryLevel = -1;
        if (VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext()).
                    registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
                    intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }
        return batteryLevel;
    }

    private void addMethodChannel() {
        if (flutterEngine == null) {
            LogUtils.d("addMethodChannel error flutterEngine == null");
            return;
        }
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), METHOD_CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                        // TODO
                        if (call.method.equals("getBatteryLevel")) {
                            int batteryLevel = getBatteryLevel();
                            if (batteryLevel != -1) {
                                result.success(batteryLevel);
                            } else {
                                result.error("UNAVAILABLE", "Battery level not available.", null);
                            }
                        } else if (call.method.equals("getAlbumJsonInfo")) {
                            String platformbid = call.argument("platformbid");
                            String platform = call.argument("platform");
//                            LogUtils.d("getAlbumJsonInfo----platformbid = " + platformbid + "  platform=" + platform);
                            Map<String, String> map = new HashMap<String, String>();
                            map.put(DTransferConstants.ALBUM_IDS, platformbid);
                            CommonRequest.getBatch(map, new IDataCallBack<BatchAlbumList>() {

                                @Override
                                public void onSuccess(BatchAlbumList batchAlbumList) {
                                    if (batchAlbumList.getAlbums() != null && batchAlbumList.getAlbums().size() > 0) {
                                        result.success(new Gson().toJson(batchAlbumList.getAlbums().get(0)));
                                    } else {
                                        result.error("cannot find Album info platformbid=" + platformbid, null, null);
                                    }
                                }

                                @Override
                                public void onError(int i, String s) {
                                    LogUtils.e("onError i=" + i + "  s=" + s);
                                    result.error(s, null, null);
                                }
                            });
                        } else if (call.method.equals("getChaptersJsonInfo")) {
                            String platformbid = call.argument("platformbid");
                            String platform = call.argument("platform");
                            int page = call.argument("page");
                            int pageSize = call.argument("pageSize");
//                            LogUtils.d("getAlbumJsonInfo----platformbid = " + platformbid + "  platform=" + platform + "  page=" + page + "  pageSize=" + pageSize);
                            Map<String, String> map = new HashMap<String, String>();
                            map.put(DTransferConstants.ALBUM_ID, platformbid);
//                            map.put(DTransferConstants.SORT, "desc");
                            map.put(DTransferConstants.PAGE, "" + page);
                            map.put(DTransferConstants.PAGE_SIZE, "" + pageSize);
                            CommonRequest.getTracks(map, new IDataCallBack<TrackList>() {

                                @Override
                                public void onSuccess(TrackList trackList) {
//                                    LogUtils.d("onSuccess  trackList.getTracks.size=" + trackList.getTracks().size());
                                    result.success(new Gson().toJson(trackList.getTracks()));
                                }

                                @Override
                                public void onError(int i, String s) {
                                    LogUtils.e("onError i=" + i + "  s=" + s);
                                    result.error(s, null, null);
                                }
                            });
                        } else if (call.method.equals("playList")) {
                            String channelListJson = call.argument("listData");
                            String platform = call.argument("platform");
                            boolean playNow = call.argument("playNow");
                            LogUtils.d("----playList platform=" + platform);
//                            LogUtils.d(channelListJson);
                            MyPlayList playList = new Gson().fromJson(channelListJson, MyPlayList.class);
                            LogUtils.d("----playList bookName=" + playList.bookName);
                            List<Track> trackList = new ArrayList<>();
                            LogUtils.d("----playList len=" + playList.list.size());
                            for (MyPlayList.MyTrack t : playList.list) {
                                Track track = new Track();
                                track.setKind(PlayableModel.KIND_TRACK);
                                track.setTrackTitle(t.trackTitle);
                                if (!TextUtils.isEmpty(t.playUrl32)) {
                                    track.setPlayUrl32(t.playUrl32);
                                }
                                track.setTrackIntro(t.trackIntro);
                                track.setDataId(t.dataId);
                                track.setCoverUrlMiddle(t.pic);
                                track.setDuration(t.duration);
                                trackList.add(track);
                            }
                            saveNowPlayBookName(playList.bookName);
                            if (playList.playModel == 0) {
                                XmPlayerManager.getInstance(getApplicationContext()).setPlayMode(XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP);
                            } else {
                                XmPlayerManager.getInstance(getApplicationContext()).setPlayMode(XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP);
                            }
                            if (playNow) {
                                XmPlayerManager.getInstance(getApplicationContext()).playList(trackList, playList.index);
                            } else {
                                XmPlayerManager.getInstance(getApplicationContext()).setPlayList(trackList, playList.index);
                            }
                            notifyPlayStatusUpdate();
                            result.success(true);
                        } else if (call.method.equals("playerPause")) {
                            String platform = call.argument("platform");
                            LogUtils.d("----playerPause platform=" + platform);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            XmPlayerManager.getInstance(getApplicationContext()).pause();
//                            }
                            result.success(true);
                        } else if (call.method.equals("playerPlay")) {
                            String platform = call.argument("platform");
                            LogUtils.d("----playerPlay platform=" + platform);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            XmPlayerManager.getInstance(getApplicationContext()).play();
//                            }
                            result.success(true);
                        } else if (call.method.equals("playerNext")) {
                            String platform = call.argument("platform");
                            LogUtils.d("----playerNext platform=" + platform);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            XmPlayerManager.getInstance(getApplicationContext()).playNext();
//                            }
                            result.success(true);
                        } else if (call.method.equals("playerPrev")) {
                            String platform = call.argument("platform");
                            LogUtils.d("----playerPrev platform=" + platform);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            XmPlayerManager.getInstance(getApplicationContext()).playPre();
//                            }
                            result.success(true);
                        } else if (call.method.equals("setPlayModel")) {
                            String platform = call.argument("platform");
                            int model = call.argument("model");
                            LogUtils.d("----setPlayModel platform=" + platform + "  model=" + model);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            if (model == 0) {
                                XmPlayerManager.getInstance(getApplicationContext()).setPlayMode(XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP);
                            } else {
                                XmPlayerManager.getInstance(getApplicationContext()).setPlayMode(XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP);
                            }
//                            }
                            result.success(true);

                        } else if (call.method.equals("getNowPlayList")) {
                            LogUtils.d("----getNowPlayList");
                            List<Track> trackList = XmPlayerManager.getInstance(getApplicationContext()).getPlayList();
                            List<MyPlayList.MyTrack> list = new ArrayList<>();
                            if (trackList != null && trackList.size() > 0) {
                                for (Track track : trackList) {
                                    MyPlayList.MyTrack myTrack = new MyPlayList.MyTrack();
                                    myTrack.dataId = track.getDataId();
                                    myTrack.playUrl32 = track.getPlayUrl32();
                                    myTrack.trackIntro = track.getTrackIntro();
                                    myTrack.trackTitle = track.getTrackTitle();
                                    myTrack.pic = track.getCoverUrlMiddle();
                                    myTrack.duration = track.getDuration();
                                    list.add(myTrack);
                                }
                            }

                            MyPlayList playList = new MyPlayList();
                            playList.index = XmPlayerManager.getInstance(getApplicationContext()).getCurrentIndex();
                            XmPlayListControl.PlayMode pm = XmPlayerManager.getInstance(getApplicationContext()).getPlayMode();
                            if (pm != XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP) {
                                playList.playModel = 1;
                            } else {
                                playList.playModel = 0;
                            }
                            playList.list = list;
                            result.success(new Gson().toJson(playList));
                        } else if (call.method.equals("seekToByPercent")) {
                            String platform = call.argument("platform");
                            double percent = call.argument("percent");
                            LogUtils.d("----seekToByPercent platform=" + platform + " percent=" + percent);
//                            if (platform == null || platform.equals(PLATFOEM_XMLY)) {
                            XmPlayerManager.getInstance(getApplicationContext()).seekToByPercent((float) percent);
//                            }
                            result.success(true);

                        } else {
                            result.notImplemented();
                        }
                    }
                });
    }

    private void addEventChannel() {
        if (flutterEngine == null) {
            LogUtils.d("addEventChannel error flutterEngine == null");
            return;
        }
        new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), EVENT_CHANNEL).setStreamHandler(
                new EventChannel.StreamHandler() {
                    @Override
                    public void onListen(Object args, final EventChannel.EventSink events) {
                        LogUtils.d("---addEventChannel onListen");
                        MyApplication.eventSink = events;
                    }

                    @Override
                    public void onCancel(Object args) {
                        LogUtils.d("---addEventChannel onCancel");
                    }
                }
        );
    }

    private void saveNowPlayBookName(String name) {
        SharedPreferences preferences = getApplicationContext().getSharedPreferences("settings", 0);
        preferences.edit().putString("nowPlayBookName", name).commit();
    }

    private void notifyPlayStatusUpdate() {
//        Intent intent = MyService.getPlayIntent(getApplicationContext(), MyService.ACTION_STATUS_UPDATE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(intent);
//        } else {
//            startService(intent);
//        }
    }
}
